package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IEmpCardDAO;
import org.jsola.hr.dto.EmpCardAddDTO;
import org.jsola.hr.dto.EmpCardDTO;
import org.jsola.hr.dto.EmpCardUpdateDTO;
import org.jsola.hr.entity.EmpCardDO;
import org.jsola.hr.query.EmpCardQuery;
import org.jsola.hr.service.IEmpCardService;
import org.jsola.hr.vo.EmpCardListVO;
import org.jsola.hr.vo.EmpCardVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrEmpCardServiceImpl")
public class EmpCardServiceImpl implements IEmpCardService {

    @Autowired
    private IEmpCardDAO empCardDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpCardVO save(EmpCardAddDTO empCardAddDTO, TokenUser tokenUser) {
        // 转DO
        EmpCardDO empCardDO = empCardAddDTO.to(EmpCardDO.class);

        // 校验员工和公司
        checkEmpAndCompany(empCardDO.getEmpId(), empCardDO.getCompanyId(), tokenUser.getSiteId());

        // 保存
        empCardDO = save(empCardDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return empCardDO.to(EmpCardVO.class);
    }

    /**
     * 校验员工和公司
     *
     * @param empId     员工id
     * @param companyId 公司id
     * @param siteId    站点
     */
    private void checkEmpAndCompany(String empId, String companyId, String siteId) {
        ParamException.hasLength(empId, "员工id不能为空");
        ParamException.hasLength(companyId, "公司id不能为空");
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(EmpCardUpdateDTO empCardUpdateDTO, TokenUser tokenUser) {
        //转DO
        EmpCardDO empCardDO = empCardUpdateDTO.to(EmpCardDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(empCardDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... empCardIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) empCardIds);
    }


    @Override
    public EmpCardVO selectById(String empCardId, String siteId) {
        EmpCardDO empCardDO = selectDOById(empCardId, siteId);
        if (empCardDO == null) {
            return null;
        }
        return empCardDO.to(EmpCardVO.class);
    }

    @Override
    public List<EmpCardListVO> select(EmpCardQuery empCardQuery, String siteId) {
        List<EmpCardDO> empCardDOList = selectDO(empCardQuery, siteId);
        if(CollectionUtils.isEmpty(empCardDOList)) {
            return empCardDOList == null ? null : new ArrayList<>();
        }
        return empCardDOList.stream()
                .map(empCardDO -> empCardDO.to(EmpCardListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(EmpCardQuery empCardQuery, String siteId) {
        Example example = buildExample(empCardQuery,siteId);
        return empCardDAO.selectCountByExample(example);
    }

    @Override
    public Page<EmpCardListVO> selectPage(EmpCardQuery empCardQuery, String siteId) {
        Example example = buildExample(empCardQuery,siteId);
        Page<EmpCardDO> page = empCardDAO.selectPageByExample(example,
                empCardQuery.getPageNo(),
                empCardQuery.getPageSize());

        return page.to(EmpCardListVO.class);
    }

    @Override
    public EmpCardDO selectDOById(String empCardId, String siteId) {
        return listById(empCardId, siteId);
    }

    @Override
    public List<EmpCardDO> selectDO(EmpCardQuery empCardQuery, String siteId) {
        Example example = buildExample(empCardQuery,siteId);
        return empCardDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void deleteByCompanyId(String companyId, TokenUser tokenUser) {
        Example example = new Example(EmpCardDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        // 逻辑删除
        List<EmpCardDO> list = empCardDAO.selectByExample(example);
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void publishEmpCardList(List<EmpCardDTO> empCardList, String companyId, String empId, TokenUser tokenUser) {
        // 删除某个员工所有的
        deleteByEmpId(empId, tokenUser);

        if (CollectionUtils.isEmpty(empCardList)) {
            return;
        }

        empCardList.forEach(
                empCardDTO -> {
                    empCardDTO.setCompanyId(companyId);
                    empCardDTO.setEmpId(empId);
                    // 新增
                    EmpCardAddDTO empCardAddDTO = empCardDTO.to(EmpCardAddDTO.class);
                    save(empCardAddDTO, tokenUser);
                }
        );
    }

    @Override
    public List<EmpCardDO> listByEmpId(String empId, String siteId) {
        Example example = new Example(EmpCardDO.class);
        example.and()
                .andEqualTo("empId", empId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 逻辑删除
        return empCardDAO.selectByExample(example);
    }

    /**
     * 删除某个员工所有的
     *
     * @param empId     员工id
     * @param tokenUser 当前用户
     */
    private void deleteByEmpId(String empId, TokenUser tokenUser) {
        // 逻辑删除
        List<EmpCardDO> list = listByEmpId(empId, tokenUser.getSiteId());
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }


    /**
     * 根据查询参数，构建example

     * @param empCardQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(EmpCardQuery empCardQuery, String siteId) {
        Example example = new Example(EmpCardDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (empCardQuery.getEmpId() != null) {
            example.and().andLike("empId", "%" + empCardQuery.getEmpId() + "%");
        }
        if (empCardQuery.getType() != null) {
            example.and().andEqualTo("type", empCardQuery.getType());
        }
        if (empCardQuery.getNumber() != null) {
            example.and().andLike("number", "%" + empCardQuery.getNumber() + "%");
        }
        if (empCardQuery.getPhoto() != null) {
            example.and().andLike("photo", "%" + empCardQuery.getPhoto() + "%");
        }
        if (empCardQuery.getSort() != null) {
            example.and().andEqualTo("sort", empCardQuery.getSort());
        }
        if (empCardQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", empCardQuery.getCompanyId());
        }
        if (empCardQuery.getGmtCreateStart() != null &&
                empCardQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", empCardQuery.getGmtCreateStart(),
                    empCardQuery.getGmtCreateEnd());
        }
        if (empCardQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + empCardQuery.getCreateUserId() + "%");
        }
        if (empCardQuery.getGmtModifiedStart() != null &&
                empCardQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", empCardQuery.getGmtModifiedStart(),
                    empCardQuery.getGmtModifiedEnd());
        }
        if (empCardQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + empCardQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,empCardQuery.getOrders());
        return example;
    }
}




